package com.fin.zw.aiqas.service;

import com.alibaba.fastjson.JSONObject;
import com.fin.zw.aiqas.model.component.JsonDataModel;
import com.fin.zw.aiqas.util.BadRequestException;
import com.fin.zw.aiqas.util.FileTransJavaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("fileTransService")
public class FileTransService {

    // 以4开头的状态码是客户端错误
    private static final Pattern PATTERN_CLIENT_ERR = Pattern.compile("4105[0-9]*");
    // 以5开头的状态码是服务端错误
    private static final Pattern PATTERN_SERVER_ERR = Pattern.compile("5105[0-9]*");
    private final static Logger log = LoggerFactory.getLogger(QcTaskInfoService.class);
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.appKey}")
    private String appKey;
    @Value("${file.server.url}")
    private String fileServerUrl;

    public static void main(String[] args) {
        String url = "http://114.116.39.18:8810/read/data/robot/asr_robot/src/record/JI8684wo/0001/admin/20191126/";
        List<String> list = new ArrayList<>();
        list.add(url + "约定还款时间.wav");
        list.add(url + "隐晦的恐吓.wav");
        list.add(url + "小心点他在外面欠钱了.wav");
        list.add(url + "未约定还款时间3.wav");
        list.add(url + "未约定还款时间2.wav");
        list.add(url + "未约定还款时间1.wav");
        list.add(url + "违约2次无施压.wav");
        list.add(url + "跳票5次无施压.wav");
        list.add(url + "跳票2次无施压.wav");
        list.add(url + "上传实名人信息.wav");
        list.add(url + "4次跳票无施压.wav");
        list.forEach(e -> {
            String result = FileTransJavaUtil.audioToText("LTAI4FwkA2CPc5QYoV7cotWR", "k3yA7KlU5POMC9BQtcwrzDCCPW5Z05", "1ctWhebnIHiOmLgx", e);
            log.info(result);
            result = formatResult(result);
            System.out.println(result);
        });
    }

    /**
     * 对阿里云语音翻译文件的结果转化
     *
     * @param result
     */
    public static String formatResult(String result) {
        List<JsonDataModel> list = new ArrayList<>();
        try {
            log.info("读取的文件信息:{}", result);
            if (result == null) throw new BadRequestException("", "语音文件翻译失败!!！");
            JSONObject jsonResult = JSONObject.parseObject(result);
            // 解析并输出相关结果内容
            log.info("获取文件中转写回调结果:{}", result);
            log.info("TaskId:{}", jsonResult.getString("TaskId"));
            log.info("StatusCode: {}", jsonResult.getString("StatusCode"));
            log.info("StatusText: {}", jsonResult.getString("StatusText"));
            Matcher matcherClient = PATTERN_CLIENT_ERR.matcher(jsonResult.getString("StatusCode"));
            Matcher matcherServer = PATTERN_SERVER_ERR.matcher(jsonResult.getString("StatusCode"));
            // 以2开头状态码为正常状态码，回调方式方式正常状态只返回"21050000"
            if ("21050000".equals(jsonResult.getString("StatusCode"))) {
                log.info("解析完成时间: " + jsonResult.getString("SolveTime"));
                log.info("BizDuration: " + jsonResult.getString("BizDuration"));
                JSONObject sentences = null;
                for (int i = 0; i < jsonResult.getJSONObject("Result").getJSONArray("Sentences").size(); i++) {
                    sentences = jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i);
                    log.info("Result.Sentences[" + i + "].BeginTime: " + sentences.getString("BeginTime"));
                    log.info("Result.Sentences[" + i + "].EndTime: " + sentences.getString("EndTime"));
                    log.info("Result.Sentences[" + i + "].SilenceDuration: " + sentences.getString("SilenceDuration"));
                    log.info("Result.Sentences[" + i + "].Text: " + sentences.getString("Text"));
                    log.info("Result.Sentences[" + i + "].ChannelId: " + sentences.getString("ChannelId"));
                    log.info("Result.Sentences[" + i + "].SpeechRate: " + sentences.getString("SpeechRate"));
                    log.info("Result.Sentences[" + i + "].EmotionValue: " + sentences.getString("EmotionValue"));
                    JsonDataModel model = new JsonDataModel();
                    model.setBg(sentences.getString("BeginTime"));
                    model.setEd(sentences.getString("EndTime"));
                    model.setOnebest(sentences.getString("Text"));
                    model.setSpeaker((Integer.valueOf(sentences.getString("ChannelId")) + 1) + "");
                    list.add(model);
                }
            } else if (matcherClient.matches()) {
                log.info("状态码以4开头表示客户端错误......");
            } else if (matcherServer.matches()) {
                log.info("状态码以5开头表示服务端错误......");
            } else {
            }
        } catch (BadRequestException e) {
            e.printStackTrace();
        }
        return JSONObject.toJSONString(list);
    }

    /**
     * 组装文件路径,及阿里云的鉴权参数提交
     * 提交文件,进行质检
     *
     * @param filePath 文件路径
     * @return
     */

    public String speechRecognition(String filePath) {
        log.info("即将提交语音文件: {}", filePath);
//        String filename = "";
//        if (filePath.contains("\\")){
//           String [] fps =  filePath.split("\\\\");
//           filename = "data/poc_test/"+fps[fps.length-1];
//        }else
//        {
//            filename = filePath;
//        }

        String fileUrl = fileServerUrl + filePath ;//filename;
        //String fileUrl =  filePath;
        log.info("提交的文件为: {}", fileUrl);
        return FileTransJavaUtil.audioToText(accessKeyId, accessKeySecret, appKey, fileUrl);
    }


}
